<?php
require '../function.php';
if(!isset($_SESSION['id']) || PHP_INT_MAX != $_SESSION['id']) {
	echo '<script language="javascript">window.top.location.replace(\'login.php\');</script>';
	exit;
}
if(isset($_POST['create_code'])) {
	// create random string
	$values = array();
	for ($i = 0; $i < 100; $i ++)
	{
		$shuffled = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz');
		$rand = md5(microtime().substr($shuffled, 0, 32));
		$type = rand(0, 1);
		$good_id = rand(1, 4);
		$values[] = "('$rand', $type, $good_id)";
	}
	if (!empty($values))
	{
		$conn = conn();
		$sql = "INSERT INTO charge_codes (charge_code, type, good_id) VALUES ".implode(',', $values);
		mysql_query($sql, $conn);
	}
}
if (isset($_GET['good_id']))
{
	$filter_good_id = $_GET['good_id'];
}
else 
{
	$filter_good_id = 1;
}
?><html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<style type="text/css">
			table {
				border-collapse: collapse;
				border: 1px gray solid;
			}
			table tr td.expire {
				width: 100px;
				text-align: center;
			}
		</style>
	</head>
	<body style="text-align:center;font-family:Arial;">
		<p>充值密码列表：</p>
		<p style="line-height: 25px;">
<?php 
$conn = conn();
echo '<select onchange="window.location.href=\'charge_code.php?good_id=\'+this.value"><option value="0">根据有效期筛选充值密码</option>
	<option value="1">1 个月</option>
	<option value="2">3 个月</option>
	<option value="3">6 个月</option>
	<option value="4">1 年</option>
</select><br /><br />';
$sql = "SELECT charge_code, name good FROM charge_codes JOIN goods ON good_id = goods.id WHERE type = 0 AND goods.id = $filter_good_id LIMIT 0, 10";
$result = mysql_query($sql, $conn);
$count = mysql_num_rows($result);
if ($count > 0)
{
	echo '<table border="1">';
	echo '<tr><td><b>密码</b></td><td class="expire"><b>有效期</b></td></tr>';
}
while ($row = mysql_fetch_assoc($result))
{
	echo '<tr><td>', $row['charge_code'] , '</td><td class="expire">', str_replace('year', '年', preg_replace('/months?/', '个月', $row['good'])), '</td></tr>';
}
if ($count > 0)
{
	echo '</table>';
}
if (0 == $count)
	echo '暂时没有充值密码，你可以点这里生成，<form method="post" action="charge_code.php"><input name="create_code" type="submit" value="生成充值密码" /></form>';
?>
		</p>
	</body>
</html>